package com.softlab.retailwholesalesystem.controller;

import com.softlab.retailwholesalesystem.entity.UserEntity;
import com.softlab.retailwholesalesystem.service.IUserService;
import com.softlab.retailwholesalesystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
public class UserController extends BaseController{

    @Autowired
    IUserService userService;

    @RequestMapping("/login")
    public JsonResult<UserEntity> login(UserEntity user) {
        UserEntity login = userService.login(user);
        UserEntity user1=new UserEntity();
        user1.setUserId(login.getUserId());
        user1.setUsername(login.getUsername());
        user1.setRoleId(login.getRoleId());
        return new JsonResult<>(200,"登录成功",user1);
    }

    @RequestMapping("/register")
    public JsonResult<Void> registerUser(UserEntity user){
        userService.registerUser(user);
        return new JsonResult<>(200,"注册成功");
    }

    @PutMapping("/user/password")
    public JsonResult<Void> changePassword(@RequestBody UserEntity user){
        userService.changePassword(user);
        return new JsonResult<>(200,"密码修改成功");
    }

    @PutMapping("/user/update")
    public JsonResult<Void> updateUser(@RequestBody UserEntity user){
        userService.updateById(user);
        return new JsonResult<>(200,"修改成功");
    }

    @GetMapping("/user/search")
    public JsonResult<List<UserEntity>> searchUser(UserEntity user){
        List<UserEntity> list = userService.getUserByCondition(user);
        for (UserEntity entity : list) {
            entity.setPassword("");
            entity.setSalt("");
        }
        return new JsonResult<>(200,"查询成功",list);
    }

    @GetMapping("/user")
    public JsonResult<List<UserEntity>> getAllUsers(){
        UserEntity user=new UserEntity();
        List<UserEntity> list = userService.getUserByCondition(user);
        for (UserEntity entity : list) {
            entity.setPassword("");
            entity.setSalt("");
        }
        return new JsonResult<>(200,"查询成功",list);
    }

    @DeleteMapping("/user/{id}")
    public JsonResult<Void> deleteUser(@PathVariable Integer id){
        UserEntity user = new UserEntity();
        user.setUserId(id);
        user.setIsDelete(1);
        userService.updateById(user);
        return new JsonResult<>(200,"删除成功");
    }
}
